(ns dao
 (use clojure.contrib.sql)
 (use clojure.contrib.sql.internal))

(defn properties_seq
  "属性文件到map"
  [file]
  (let [ p (java.util.Properties.)
      is (ClassLoader/getSystemResourceAsStream file)]
  (do
    (. p load is)
    (loop [r {}  s (seq p)]
      (if s
        (recur (conj r [(key (first s)) (val (first s))]) (next s))
       r
       ))
    )))

 (defn sql 
   ([s] (sql "sql.properties" s))
   ([file sqlname]
   ((properties_seq file)  sqlname)))

(def dbspec
  {:classname "oracle.jdbc.driver.OracleDriver"
   :user "qc"
   :password "w123456"
   :subprotocol "oracle:thin:@192.168.1.8:1521"
   :subname "QCDB"
   })

(def conn (get-connection dbspec))

(defn select
 "sql 语句到数据集合"  
  [sqlname  & params]
  (do
    (println (vec (cons (str (sql "sql.properties" sqlname)) params)))
  (with-connection dbspec (with-query-results rs (vec (cons (str (sql "sql.properties" sqlname)) params))
                           (loop [all [] rs rs]
                             (if (seq rs)
                               (recur (conj all (first rs)) (next rs))
                               all))))))

(defn delete
  "根据条件删除数据"
  [sqlname & params]
  ( do
    (println (sql sqlname) [params])
    (with-connection dbspec
      (do-prepared  (sql sqlname) params))))

(defn do-insert
  "根据sql插入数据"
  [sql data]
  (with-open [stmt (.prepareStatement      (connection) sql)]
    (doseq [da data]
      (doseq [[index value] (map vector (iterate inc 1) da)]
        (.setObject stmt index value))
      (.addBatch stmt))
     (.executeBatch stmt)
      ))

(defn insert
  "写数据"
   [sqlname data]
  (do (println (sql sqlname) data)
 (with-connection dbspec (do-insert (sql sqlname) data))))

(defn zs-day-eval-data [startday endday]
  (select "zsDayEvalSelectSql" endday endday startday endday))

(defn zs-day-eval-delete [startday endday]
  (delete "zsDayEvalDeleteSql" startday endday))

(defn zs-day-eval-insert [data]
  (insert "zsDayEvalInsertSql" data))

(zs-day-eval-insert [["1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" ]])
(zs-day-eval-delete "1" "2")
(def f (zs-day-eval-data "20081201" "20081211"))
f











